import requests
from app.utils.db import get_connection
from app.conf.config import Config

def exchange_access_token(shop, code):
    url = f"https://{shop}/admin/oauth/access_token"
    data = {
        "client_id": Config.SHOPIFY_API_KEY,
        "client_secret": Config.SHOPIFY_API_SECRET,
        "code": code
    }
    resp = requests.post(url, json=data)
    resp.raise_for_status()
    return resp.json()

def save_access_token(shop, access_token):
    conn = get_connection()
    try:
        with conn.cursor() as cursor:
            sql = "REPLACE INTO app_user (shop, access_token) VALUES (%s, %s)"
            cursor.execute(sql, (shop, access_token))
        conn.commit()
    finally:
        conn.close()